# routers/ownedit.py
from fastapi import APIRouter, Request, Depends, HTTPException, status,Cookie
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from typing import Optional
import re
from urllib.parse import unquote  # 导入 unquote 用于解码
from sqlalchemy.orm import Session
from utils import validate_session
# 导入数据库和模型
from database import get_db
from models import User

router = APIRouter()
templates = Jinja2Templates(directory="templates")

# 关键修复：添加自定义过滤器
templates.env.filters["urldecode"] = unquote

# 哈希密码。不会用
# pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")   

# 表单验证模型
class UserUpdateForm:
    def __init__(
        self,
        realname: str,  # 改为小写参数名
        contact: Optional[str] = None,
        password: Optional[str] = None,
        confirm_password: Optional[str] = None
    ):
        self.RealName = realname.strip() if realname else ""  # 空值处理
        self.Contact = contact.strip() if contact else ""
        self.Password = password
        self.confirm_password = confirm_password

def validate_contact(Contact: str) -> bool:
    """验证联系方式格式（电话或邮箱）"""
    # 手机号验证
    phone_pattern = r"^1[3-9]\d{9}$"
    # 邮箱验证
    email_pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
    
    return re.match(phone_pattern, Contact) or re.match(email_pattern, Contact)

@router.get("/ownedit", response_class=HTMLResponse)
async def ownedit_page(request: Request,  
                    SessionId: Optional[str] = Cookie(None),
                    UserName: Optional[str] = Cookie(None),
                    db: Session = Depends(get_db)):
    """
    显示用户信息编辑页面
    """
    if not SessionId or not UserName or not validate_session(SessionId, UserName):
        return RedirectResponse(url="/")

    # 从cookie中获取当前用户名
    encoded_UserName = request.cookies.get("UserName")
    if not encoded_UserName:
        return RedirectResponse("/login", status_code=status.HTTP_302_FOUND)
    
    
    # 关键修复：解码用户名
    UserName = unquote(encoded_UserName)
    
    # 从数据库获取用户信息
    user = db.query(User).filter(User.UserName == UserName).first()
    if not user:
        return RedirectResponse("/login", status_code=status.HTTP_302_FOUND)
    
    # 渲染模板并传递用户信息
    return templates.TemplateResponse(
        "ownedit.html",
        {
            "request": request,
            "RealName": user.RealName,
            "UserName": user.UserName,
            "Contact": user.Contact or ""
        }
    )

@router.post("/ownedit", response_class=HTMLResponse)
async def update_user_info(
    request: Request, 
    db: Session = Depends(get_db)
):
    """
    处理用户信息更新
    """
    # 获取当前用户名
    encoded_UserName = request.cookies.get("UserName")
    if not encoded_UserName:
        return RedirectResponse("/login", status_code=status.HTTP_302_FOUND)
    
    # 关键修复：解码用户名
    UserName = unquote(encoded_UserName)
    
    # 从数据库获取用户
    user = db.query(User).filter(User.UserName == UserName).first()
    if not user:
        return RedirectResponse("/login", status_code=status.HTTP_302_FOUND)
    
    # 解析表单数据
    form_data = await request.form()
    form = UserUpdateForm(
        realname=form_data.get("realname"),  # 小写r
        contact=form_data.get("contact"),    # 小写c
        password=form_data.get("password"),
        confirm_password=form_data.get("confirm_password")
    )
    
    # 验证数据
    errors = []

    form.RealName = form.RealName.strip()  # 修剪空格
    
    # # 验证真实姓名
    # if not form.RealName:
    #     errors.append("真实姓名不能为空")
    # elif len(form.RealName) < 2:
    #     errors.append("真实姓名不能少于2个字符")
    
    # 验证联系方式（可选）
    # if form.Contact and not validate_contact(form.Contact):
    #     errors.append("联系方式格式不正确（请输入有效的手机号或邮箱）")
    
    # 验证密码
    if form.Password:
        if len(form.Password) < 6:  # 改为6位验证
            errors.append("密码长度不能少于6位")
        if form.Password != form.confirm_password:
            errors.append("两次输入的密码不一致")
    
    # 如果有错误，返回错误信息
    if errors:
        return templates.TemplateResponse(
            "ownedit.html",
            {
                "request": request,
                "errors": errors,
                "RealName": form.RealName,
                "UserName": user.UserName,
                "Contact": form.Contact
            },
            status_code=400
        )
    
    try:
        # 更新用户信息
        user.RealName = form.RealName
        user.Contact = form.Contact
        
        # 如果设置了新密码，更新密码
        if form.Password:
            user.set_password(form.Password)
        
        # 提交到数据库
        db.commit()
        db.refresh(user)
        
        # 创建响应
        response = templates.TemplateResponse(
            "ownedit.html",
            {
                "request": request,
                "success": "用户信息更新成功",
                "RealName": user.RealName,
                "UserName": user.UserName,
                "Contact": user.Contact or ""
            }
        )
        
        # 更新cookie中的用户信息（关键修复：进行URL编码）
        from urllib.parse import quote
        response.set_cookie(key="RealName", value=quote(user.RealName))
        response.set_cookie(key="UserName", value=quote(user.UserName))
        
        return response
    
    except Exception as e:
        db.rollback()
        return templates.TemplateResponse(
            "ownedit.html",
            {
                "request": request,
                "error": f"更新失败: {str(e)}",
                "RealName": form.RealName,
                "UserName": user.UserName,
                "Contact": form.Contact
            },
            status_code=500
        )